const express = require('express')
const app = express()
const path = require('path')

app.use((req,res,next)=>{

    let dataStr = ""
    req.on("data",chunk=>{
        dataStr += chunk.toString()
    })

    req.on("end",()=>{
        console.log(dataStr); // name=lifeiyu123&age=12300&sex=男
        // let dataObj = {}
        // dataStr.split('&').forEach((item)=>{
        //    const [key , value] = item.split('=')
        //    dataObj[key] = value
        // })

        const dataObj = dataStr.split('&').reduce((prev,item)=>{
            const[key , value] = item.split('=')
            prev[key] = value
            return prev
        },{})

        req.body = dataObj
        next()
    })

    
})


app.post("/adduser",(req,res)=>{
    console.log(req.body);
    const{
        name,
        age,
        sex
    } = req.body

    if(!name || !age || !sex){
        return res.send({
            code: 10001,
            msg: "添加失败",
            data: {
                result: "就是失败"
            }
        })
    }

    res.send({
        code: 10000,
        msg: "添加成功",
        data: {
            result: "成功了"
        }
    })


})




//搭建静态资源路由
app.get("/1",(req,res)=>{
    const filePath = path.resolve(__dirname,"./01.post请求手写中间件.html")
    res.sendFile(filePath)
})

app.listen(3000,()=>{
    console.log("服务器成功请访问: http://127.0.0.1:3000");
})